package com.station.search.controller;

import com.station.search.common.domain.WebResponse;
import com.station.search.common.domain.WebResponseBuilder;
import com.station.search.common.util.PasswordUtil;
import com.station.search.constant.UserDeactivageEnum;
import com.station.search.domain.SystemUser;
import com.station.search.domain.converter.SystemUserConverter;
import com.station.search.domain.dto.SystemUserDTO;
import com.station.search.domain.vo.SystemUserVO;
import com.station.search.service.SystemUserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: JT
 * @date: 2021/9/8
 * @Title: 系统用户 web控制器
 */
@RestController
@RequestMapping("/system/users")
public class SystemUserController {

    @Resource
    private SystemUserService systemUserService;

    @PostMapping
    public WebResponse addUser(@RequestBody SystemUserVO systemUserVO) {
        SystemUser systemUser = SystemUserConverter.INSTANCE.voToDo(systemUserVO);

        if (StringUtils.isEmpty(systemUser.getIsDeactivage())) {
            systemUser.setIsDeactivage(UserDeactivageEnum.NOT_DEACTIVAGE.getValue());
        }

        int salt = systemUser.getUsername().hashCode();
        // 密码加密方式  md5(原密码+用户名Hash)
        systemUser.setPassword(PasswordUtil.encode(systemUser.getPassword(), String.valueOf(salt)));
        systemUserService.save(systemUser);
        return WebResponseBuilder.ok("添加系统用户[{}]成功！", systemUser.getUsername());
    }

    @PutMapping("/{userId}")
    public WebResponse modifyUser(@PathVariable("userId") Long userId, @RequestBody SystemUserVO systemUserVO) {
        SystemUser systemUser = SystemUserConverter.INSTANCE.voToDo(systemUserVO);

        systemUser.setId(userId);
        if (StringUtils.isEmpty(systemUser.getIsDeactivage())) {
            systemUser.setIsDeactivage(UserDeactivageEnum.NOT_DEACTIVAGE.getValue());
        }

        int salt = systemUser.getUsername().hashCode();
        // 密码加密方式  md5(原密码+用户名Hash)
        systemUser.setPassword(PasswordUtil.encode(systemUser.getPassword(), String.valueOf(salt)));
        systemUserService.updateById(systemUser);
        return WebResponseBuilder.ok("修改系统用户[{}]成功！", systemUser.getUsername());
    }

    @DeleteMapping("/{userId}")
    public WebResponse deleteUser(@PathVariable("userId") Long userId) {
        systemUserService.removeById(userId);
        return WebResponseBuilder.ok("删除系统用户[{}]成功！", userId);
    }

    @GetMapping
    public WebResponse<List<SystemUserDTO>> queryUsers() {
        return WebResponseBuilder.ok("查看系统用户列表成功！")
                .data(systemUserService.list());
    }


}
